package com.zhao.reggie3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.reggie3.common.BaseContext;
import com.zhao.reggie3.common.ProductException;
import com.zhao.reggie3.damain.*;
import com.zhao.reggie3.dao.OrderMapper;
import com.zhao.reggie3.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: zhao
 * @time: 2022/8/23 19:42
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * @param
     * @return
     * @description 购物车下单
     **/
    @Override
    public void submit(Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        //当前用户的购物车数据
        List<ShoppingCart> shoppingCartlist = shoppingCartService.list(lqw);
        //判断购物车数据是否为空
        if (shoppingCartlist == null || shoppingCartlist.size() == 0) {
            throw new ProductException("购物车为空，不能下单");
        }
        //根据用户id查询用户信息
        User userbyId = userService.getById(userId);
        //根据地址id 查询地址数据
        AddressBook addressBookbyId = addressBookService.getById(orders.getAddressBookId());
        //判断地址信息是否为空
        if (addressBookbyId == null) {
            throw new ProductException("用户地址信息有误，不能下单");
        }

        //生成随机订单号
        long ordersid = IdWorker.getId();

        //原子类 AtomicInteger 保证每一次执行的金额累加计算是一个原子操作
        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细数据
        List<OrderDetail> collect = shoppingCartlist.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(ordersid);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());
        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(collect);
        //组装订单数据
            orders.setId(ordersid);
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);
            orders.setAmount(new BigDecimal(amount.get()));//总金额
            orders.setUserId(userId);
            orders.setNumber(String.valueOf(ordersid));
            orders.setUserName(userbyId.getName());
            orders.setConsignee(addressBookbyId.getConsignee());
            orders.setPhone(addressBookbyId.getPhone());
            orders.setAddress((addressBookbyId.getProvinceName() == null ? "" : addressBookbyId.getProvinceName())
                    + (addressBookbyId.getCityName() == null ? "" : addressBookbyId.getCityName())
                + (addressBookbyId.getDistrictName() == null ? "" : addressBookbyId.getDistrictName())
                + (addressBookbyId.getDetail() == null ? "" : addressBookbyId.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //清空购物车数据
        shoppingCartService.remove(lqw);

    }
}